package com.nbjtjc.safe.activiti.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.serializer.SimplePropertyPreFilter;
import com.nbjtjc.safe.activiti.mapper.FlowLeaveMapper;
import com.nbjtjc.safe.activiti.model.FlowLeave;
import com.nbjtjc.safe.activiti.model.MyProcessInstance;
import com.nbjtjc.safe.activiti.model.MyTask;
import com.nbjtjc.safe.activiti.model.RunningProcess;
import com.nbjtjc.safe.bean.Result;
import com.nbjtjc.safe.util.MyShiroUtils;
import org.activiti.engine.IdentityService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.impl.persistence.entity.TaskEntity;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.runtime.ProcessInstanceQuery;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

import static com.alibaba.fastjson.JSON.*;

/**
 * @auther guqianbin
 * @date 2018/3/27 14:56
 **/
@Service
@Deprecated
public class LeaveService {

    @Autowired
    private RepositoryService repositoryService;
    @Autowired
    private TaskService taskService;
    @Autowired
    IdentityService identityservice;
    @Autowired
    RuntimeService runtimeservice;

    @Autowired
    private FlowLeaveMapper flowLeaveMapper;

    public Result leaveApply(FlowLeave flowLeave) {
        Result result = new Result();
        flowLeave.setApplyTime(new Date());
        flowLeave.setUserId(MyShiroUtils.getSessionUserId());
        flowLeaveMapper.insert(flowLeave);
        String businessKey = String.valueOf(flowLeave.getId());
        identityservice.setAuthenticatedUserId(MyShiroUtils.getSessionUserId().toString());
        Map<String, Object> variables = new HashMap<>();
        variables.put("applyUserId", MyShiroUtils.getSessionUserId());
        ProcessInstance processInstance = runtimeservice.startProcessInstanceByKey("leave", businessKey, variables);
        String processId = processInstance.getId();
        flowLeave.setProcessInstanceId(processId);
        flowLeaveMapper.updateByPrimaryKeySelective(flowLeave);

        if (ObjectUtil.isNotNull(processInstance)) {
            RunningProcess runningProcess = new RunningProcess();
            runningProcess.setActivityid(processInstance.getActivityId());
            runningProcess.setBusinesskey(processInstance.getBusinessKey());
            runningProcess.setExecutionid(processInstance.getId());
            runningProcess.setProcessInstanceid(processInstance.getProcessInstanceId());
            result.setData(runningProcess);
        } else {
            result.setFalse("无任务");
        }
        return result;
    }

    public Result findMyLeave() {
        Result result = new Result();
        ProcessInstanceQuery query = runtimeservice.createProcessInstanceQuery();
        List<ProcessInstance> processInstances = query.processDefinitionKey("leave")
                .involvedUser(MyShiroUtils.getSessionUserId().toString()).list();
        List<RunningProcess> processes = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(processInstances)) {
            processInstances.forEach(processInstance -> {
                processes.add(processCompare(processInstance));
            });
        }
        result.setData(processes);
        return result;
    }

    public Result findDeptLeaderTask() {
        Result result = new Result();
        List<Task> taskEntities = taskService.createTaskQuery().taskDefinitionKey("deptLeaderVerify").list();
        List<FlowLeave> flowLeaves = new ArrayList<>();
        taskEntities.forEach(task -> {
            String processInstanceId = task.getProcessInstanceId();
            ProcessInstance processInstance = runtimeservice.createProcessInstanceQuery()
                    .processInstanceId(processInstanceId).singleResult();
            String businessKey = processInstance.getBusinessKey();
            FlowLeave flowLeave = flowLeaveMapper.selectByPrimaryKey(Integer.parseInt(businessKey));
            TaskEntity taskEntity= (TaskEntity) task;
            SimplePropertyPreFilter filter=new SimplePropertyPreFilter();
            filter.getIncludes().clear();
            filter.getIncludes().add("id");
            filter.getIncludes().add("processDefinitionName");
            filter.getIncludes().add("businessKey");
            filter.getIncludes().add("startUserId");
            filter.getIncludes().add("startTime");
            filter.getIncludes().add("processInstanceId");
            flowLeave.setMyTask(MyTask.getMyTask(taskEntity));
            flowLeave.setProcessInstance(MyProcessInstance.getMyProcessInstance(processInstance));
            flowLeaves.add(flowLeave);
        });
        Map<String, Object> data = new HashMap<>();
        data.put("flowLeaves", flowLeaves);
        result.setData(data);
        return result;
    }


    private RunningProcess processCompare(ProcessInstance processInstance) {
        if (ObjectUtil.isNotNull(processInstance)) {
            RunningProcess runningProcess = new RunningProcess();
            runningProcess.setActivityid(processInstance.getActivityId());
            runningProcess.setBusinesskey(processInstance.getBusinessKey());
            runningProcess.setExecutionid(processInstance.getId());
            runningProcess.setProcessInstanceid(processInstance.getProcessInstanceId());
            return runningProcess;
        } else {
            return null;
        }
    }
}
